package com.caifeng.security;

import com.caifeng.domain.ResponseCode;
import com.caifeng.domain.ServiceException;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        String token = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication().getCredentials())
                .orElseThrow(() -> new ServiceException(ResponseCode.TOKEN_INVALIDATION)).toString();

        // 将token添加到请求头中
        template.header("Authorization", token);
    }
}

